<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/24
 * Time: 13:07
 * 登录模块
 */
namespace app\home\model;

use app\home\model\Base;
use think\Exception;
use think\Log;
use think\Request;
use think\Session;
use think\Db;
use think\captcha\Captcha; //验证码用

class Login extends Base {
    /**
     * 登录验证
     */
    public function checkLoginM()
    {
        try{
            $post_param = Request::instance()->post();
            // 验证验证码
            if(!captcha_check($post_param['code'])){
                return ['code'=>1,'msg'=>'验证码不正确','param'=>'code'];
            }
            // 验证用户
            $sql_one = "SELECT * FROM yc_client WHERE number = '".$post_param['name']."' LIMIT 1";
            $user_info = Db::query($sql_one);
            if( !$user_info || !$user_info['0']['type'] ){
                return ['code'=>2,'msg'=>'用户名不存在','param'=>'name'];
            }
            // 验证密码
            $pass = md5($post_param['pass']);
            if( $pass != $user_info['0']['pass'] ) {
                return ['code'=>3,'msg'=>'密码错误','param'=>'pass'];
            }
            // 登录日志
            $login_log = $this->loginLog($user_info['0']);
            // 登陆次数+1
            $sql_two = "UPDATE yc_client SET login_number = login_number + 1 WHERE id = ".$user_info['0']['id'];
            Db::execute($sql_two);
            // 登陆成功，记录session
            Session::set('S_USER_INFO',$user_info['0']);
            return ['code'=>0,'msg'=>'登录成功！'];
        } catch (\Exception $e) {
            Log::write('登录验证异常：'.$e->getMessage(),'error');
        }
    }

    /**
     * 登录日志
     * @param array $user_info 登录用户的信息
     * @return bool 日志记录结果
     */
    protected function loginLog($user_info = [])
    {
        try {
            $login_number = $user_info['number'];   // 登录用户账号名
            $login_user_id = $user_info['id'];   // 登录用户账号ID
            $login_link_user = $user_info['link_user'];   // 登录账号联系人
            $login_user_type = '2';   // 登录账号类型 2：直接客户登录
            $login_time = time();   // 登录时间
            $login_ip = sprintf("%u",ip2long(request()->ip()));  // 登录用户IP
            $sql = "INSERT INTO yc_admin_log (`manage_name`,`user_id`,`name`,`ip`,`type`,`login_time`) VALUES ('".$login_number."','".$login_user_id."','".$login_link_user."','".$login_ip."','".$login_user_type."','".$login_time."')";
            $result = Db::execute($sql);
        } catch (Exception $e) {
            Log::write('登录日志异常：'.$e->getMessage(),'error');
        }
    }

    /**
     * 退出登录状态
     */
    public function loginOutM()
    {
        try {
            Session::delete('S_USER_INFO');
            if(Session::get('S_USER_INFO')){
                return ['code'=>1,'msg'=>'服务器异常！'];
            }
            return ['code'=>0,'msg'=>'退出登录成功！'];
        } catch (Exception $e) {
            Log::write('退出登录异常：'.$e->getMessage(),'error');
        }
    }

}